package com.neudu.glsb.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.neudu.glsb.commons.JSONReturn;
import com.neudu.glsb.dto.StatsDTO;
import com.neudu.glsb.pojo.Orders;
import com.neudu.glsb.service.MemberService;
import com.neudu.glsb.service.OrdersService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;
import org.springframework.util.StringUtils;
import java.text.SimpleDateFormat;
import java.math.RoundingMode;  // 注意：是 java.math 包，不是 java.text！import java.util.HashMap;
import java.util.Map;
@RestController
public class OrdersController {

    @Autowired
    private OrdersService ordersService;
    @Autowired
    private JSONReturn jsonReturn;
    @Autowired
    private MemberService memberService;
@PostMapping("get_all_orders")
public String getAllOrders(@RequestBody Map<String, Object> pageInfoMap) {
    try {
        Integer pageNum = (Integer) pageInfoMap.get("pageNum");
        Integer pageSize = (Integer) pageInfoMap.get("pageSize");

        // 1. 先查询所有订单数据（不先分页）
        List<Orders> allOrders = ordersService.list();

        // 2. 对全量数据按状态优先级排序（关键：排序所有数据，而非分页后的数据）
        allOrders.sort((o1, o2) -> getStatusPriority(o1.getOrderStatus()) - getStatusPriority(o2.getOrderStatus()));

        // 3. 对排序后的全量数据进行手动分页（避免PageHelper先分页导致排序失效）
        int total = allOrders.size();
        // 计算分页起始索引（防止页码超出范围）
        int startIndex = Math.max((pageNum - 1) * pageSize, 0);
        // 计算分页结束索引（防止索引超出集合长度）
        int endIndex = Math.min(startIndex + pageSize, total);
        // 截取当前页数据
        List<Orders> currentPageOrders = allOrders.subList(startIndex, endIndex);

        // 4. 构建分页信息（符合前端接收格式）
        PageInfo<Orders> pageInfo = new PageInfo<>();
        pageInfo.setList(currentPageOrders); // 当前页数据
        pageInfo.setTotal(total); // 总数据量
        pageInfo.setPageNum(pageNum); // 当前页码
        pageInfo.setPageSize(pageSize); // 每页条数
        pageInfo.setPages((total + pageSize - 1) / pageSize); // 总页数（向上取整）

        return jsonReturn.returnSuccess(pageInfo);
    } catch (Exception e) {
        e.printStackTrace();
        return jsonReturn.returnError("获取订单失败：" + e.getMessage());
    }
}

    // 查询已完成订单
    @PostMapping("get_completed_order")
    public String getCompletedOrder(@RequestBody Map<String, Object> pageInfoMap) {
        try {
            Integer pageNum = (Integer) pageInfoMap.get("pageNum");
            Integer pageSize = (Integer) pageInfoMap.get("pageSize");
            PageHelper.startPage(pageNum, pageSize);

            List<Orders> list = ordersService.listCompletedOrders();
            PageInfo<Orders> pageInfo = new PageInfo<>(list);
            return jsonReturn.returnSuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取已完成订单失败：" + e.getMessage());
        }
    }

    // 按状态和时间查询订单
    @PostMapping("get_orders_by_status_and_time")
    public String getOrdersByStatusAndTime(@RequestBody Map<String, Object> conditionMap) {
        try {
            Integer pageNum = (Integer) conditionMap.get("pageNum");
            Integer pageSize = (Integer) conditionMap.get("pageSize");
            String orderStatus = (String) conditionMap.get("orderStatus");
            String startTime = (String) conditionMap.get("startTime");
            String endTime = (String) conditionMap.get("endTime");

            PageHelper.startPage(pageNum, pageSize);
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();

            // 状态筛选（支持空值，空则查全部）
            if (!ObjectUtils.isEmpty(orderStatus)) {
                queryWrapper.eq(Orders::getOrderStatus, orderStatus);
            }

            // 时间范围筛选（修复：时间格式匹配前端传递的ISO格式）
            if (!ObjectUtils.isEmpty(startTime) && !ObjectUtils.isEmpty(endTime)) {
                queryWrapper.between(Orders::getOrderTime, startTime, endTime);
            } else if (!ObjectUtils.isEmpty(startTime)) {
                queryWrapper.ge(Orders::getOrderTime, startTime);
            } else if (!ObjectUtils.isEmpty(endTime)) {
                queryWrapper.le(Orders::getOrderTime, endTime);
            }

            List<Orders> orders = ordersService.list(queryWrapper);
            orders.sort((o1, o2) -> getStatusPriority(o1.getOrderStatus()) - getStatusPriority(o2.getOrderStatus()));

            PageInfo<Orders> pageInfo = new PageInfo<>(orders);
            return jsonReturn.returnSuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("筛选订单失败：" + e.getMessage());
        }
    }

    // 大屏叫号：获取待取餐订单
    @GetMapping("get_pending_pickup_orders")
    public String getPendingPickupOrders() {
        try {
            List<Orders> orders = ordersService.getPendingPickupOrders();
            return jsonReturn.returnSuccess(orders);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取待取餐订单失败：" + e.getMessage());
        }
    }

    // 更新为待取餐（生成取餐码）
    @PostMapping("update_order_to_pending")
    public String updateToPendingPickup(@RequestBody Map<String, Integer> orderMap) {
        try {
            Integer orderId = orderMap.get("orderId");
            if (ObjectUtils.isEmpty(orderId)) {
                return jsonReturn.returnError("订单ID不能为空");
            }

            boolean success = ordersService.updateToPendingPickup(orderId);
            if (success) {
                Orders updatedOrder = ordersService.getById(orderId);
                return jsonReturn.returnSuccess(updatedOrder);
            } else {
                return jsonReturn.returnError("更新为待取餐状态失败");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("操作失败：" + e.getMessage());
        }
    }

    // 更新为已完成
    @PostMapping("update_order_to_completed")
    public String updateToCompleted(@RequestBody Map<String, Integer> orderMap) {
        try {
            Integer orderId = orderMap.get("orderId");
            if (ObjectUtils.isEmpty(orderId)) {
                return jsonReturn.returnError("订单ID不能为空");
            }

            boolean success = ordersService.updateToCompleted(orderId);
            return success ? jsonReturn.returnSuccess("订单已标记为已完成") : jsonReturn.returnError("更新为已完成状态失败");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("操作失败：" + e.getMessage());
        }
    }

    // 模糊查询订单
    @PostMapping("get_order_by_condition")
    public String getByCondition(@RequestBody Map<String, Object> conditionMap) {
        try {
            Integer pageNum = (Integer) conditionMap.get("pageNum");
            Integer pageSize = (Integer) conditionMap.get("pageSize");
            String orderStatus = (String) conditionMap.get("orderStatus");

            PageHelper.startPage(pageNum, pageSize);
            LambdaQueryWrapper<Orders> queryWrapper = new LambdaQueryWrapper<>();
            if (!ObjectUtils.isEmpty(orderStatus)) {
                queryWrapper.like(Orders::getOrderStatus, orderStatus);
            }

            List<Orders> orders = ordersService.list(queryWrapper);
            PageInfo<Orders> pageInfo = new PageInfo<>(orders);
            return jsonReturn.returnSuccess(pageInfo);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("模糊查询失败：" + e.getMessage());
        }
    }

    // 新增订单
    @PostMapping("add_one_order")
    public String addOneOrder(@RequestBody Orders order) {
        try {
            // 新增时默认生成订单时间（避免前端传递为空）
            if (ObjectUtils.isEmpty(order.getOrderTime())) {
                order.setOrderTime(new java.util.Date());
            }
            ordersService.save(order);
            return jsonReturn.returnSuccess("订单新增成功");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("新增订单失败：" + e.getMessage());
        }
    }

    // 根据ID查询订单
    @PostMapping("get_order_by_id")
    public String getById(@RequestBody Map<String, Integer> idMap) {
        try {
            Integer id = idMap.get("id");
            if (ObjectUtils.isEmpty(id)) {
                return jsonReturn.returnError("ID不能为空");
            }
            Orders order = ordersService.getById(id);
            return jsonReturn.returnSuccess(order);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取订单详情失败：" + e.getMessage());
        }
    }

    // 修改订单
    @PostMapping("modify_order_by_id")
    public String modifyById(@RequestBody Orders order) {
        try {
            if (ObjectUtils.isEmpty(order.getId())) {
                return jsonReturn.returnError("更新失败，ID不能为空");
            }
            boolean success = ordersService.updateById(order);
            return success ? jsonReturn.returnSuccess("订单修改成功") : jsonReturn.returnError("更新失败，未找到对应订单");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("修改订单失败：" + e.getMessage());
        }
    }

    // 订单退款（修复：接口命名，避免与删除混淆）
//    @PostMapping("refund_order_by_id")
//    public String refundById(@RequestBody Map<String, Integer> idMap) {
//        try {
//            Integer id = idMap.get("id");
//            if (ObjectUtils.isEmpty(id)) {
//                return jsonReturn.returnError("ID不能为空");
//            }
//
//            Orders order = ordersService.getById(id);
//            if (order == null) {
//                return jsonReturn.returnError("未找到对应订单");
//            }
//
//            // 仅允许已完成订单退款
//            if (!"已完成".equals(order.getOrderStatus())) {
//                return jsonReturn.returnError("仅已完成订单支持退款操作");
//            }
//
//            order.setOrderStatus("已退款");
//            boolean success = ordersService.updateById(order);
//            return success ? jsonReturn.returnSuccess("订单退款成功") : jsonReturn.returnError("退款失败，更新状态失败");
//        } catch (Exception e) {
//            e.printStackTrace();
//            return jsonReturn.returnError("退款操作失败：" + e.getMessage());
//        }
//    }
    private String generateOrderRemark(List<Map<String, Object>> orderProducts) {
        StringBuilder remark = new StringBuilder();
        if (orderProducts == null || orderProducts.isEmpty()) {
            return "无商品信息";
        }
        // 遍历每类商品，拼接备注（格式：商品名称-份数-甜度-冰度-小料）
        for (Map<String, Object> product : orderProducts) {
            // 商品名称
            String productName = (String) product.get("productName");
            // 份数
            Integer quantity = (Integer) product.get("quantity");
            // 甜度
            String sweetnessName = (String) ((Map<String, Object>) product.get("sweetness")).get("name");
            // 冰度
            String iceName = (String) ((Map<String, Object>) product.get("ice")).get("name");
            // 小料（处理“无小料”场景）
            List<Map<String, Object>> ingredients = (List<Map<String, Object>>) product.get("selectedIngredients");
            String ingredientStr = ingredients.stream()
                    .filter(ing -> !"不添加小料".equals(ing.get("name"))) // 排除“不添加小料”选项
                    .map(ing -> (String) ing.get("name"))
                    .collect(Collectors.joining("、"));
            if (ingredientStr.isEmpty()) {
                ingredientStr = "无";
            }
            // 拼接单类商品备注（每行一类商品）
            remark.append(String.format("%s-%d份-%s-%s-小料：%s%n",
                    productName, quantity, sweetnessName, iceName, ingredientStr));
        }
        return remark.toString();
    }
    // 辅助方法：定义状态优先级（数字越小优先级越高）
    private int getStatusPriority(String status) {
        switch (status) {
            case "制作中": return 1;
            case "待取餐": return 2;
            case "已完成": return 3;
//            case "已退款": return 4;
            default: return 4;
        }
    }
    /**
     * 会员支付创建订单（新增）
     */
    @PostMapping("/createOrderWithMember")
    public String createOrderWithMember(@RequestBody Map<String, Object> orderMap) {
        try {
            Integer userId = (Integer) orderMap.get("userId");
            String paymentMethod = (String) orderMap.get("paymentMethod");
            BigDecimal totalAmount = new BigDecimal(orderMap.get("totalAmount").toString());
            Integer memberId = (Integer) orderMap.get("memberId");

            if (ObjectUtils.isEmpty(userId) || ObjectUtils.isEmpty(paymentMethod) || ObjectUtils.isEmpty(totalAmount) || ObjectUtils.isEmpty(memberId)) {
                return jsonReturn.returnError("参数不全");
            }

            // 1. 创建订单
            Orders order = new Orders();
            order.setUserId(userId);
            order.setOrderStatus("制作中");
            order.setOrderTime(new Date());
            order.setTotalAmount(totalAmount);
            order.setPaymentMethod(paymentMethod);
            order.setPickupCode(ordersService.generatePickupCode()); // 生成取餐码

            // 构建订单备注
            StringBuilder remark = new StringBuilder();
            List<Map<String, Object>> orderProducts = (List<Map<String, Object>>) orderMap.get("orderProducts");
            for (Map<String, Object> product : orderProducts) {
                String productName = (String) product.get("productName");
                Integer quantity = (Integer) product.get("quantity");
                String sweetnessName = (String) product.get("sweetnessName");
                String iceName = (String) product.get("iceName");
                remark.append(productName).append("-").append(quantity).append("份-").append(sweetnessName).append("-").append(iceName);

                List<Map<String, Object>> ingredients = (List<Map<String, Object>>) product.get("selectedIngredients");
                if (ingredients != null && !ingredients.isEmpty()) {
                    String ingNames = ingredients.stream()
                            .map(ing -> (String) ing.get("ingredientName"))
                            .reduce((a, b) -> a + "、" + b)
                            .orElse("");
                    remark.append("-小料：").append(ingNames);
                }
                remark.append("\n");
            }
            order.setRemark(remark.toString());

            boolean orderSuccess = ordersService.save(order);
            if (!orderSuccess) {
                return jsonReturn.returnError("订单创建失败");
            }

            // 2. 给会员增加积分（1元=1积分）
            Integer points = totalAmount.intValue();
            boolean pointsSuccess = memberService.addPoints(memberId, points);
            if (!pointsSuccess) {
                // 积分添加失败，可选择回滚订单或提示用户
                return jsonReturn.returnError("订单创建成功，但积分添加失败");
            }

            return jsonReturn.returnSuccess("订单创建成功，积分已到账");
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("创建订单失败：" + e.getMessage());
        }
    }




//新增加

    @PostMapping("get_sales_stats")
    public String getSalesStats(@RequestBody Map<String, String> params) {
        try {
            String startTime = params.get("startTime");
            String endTime = params.get("endTime");

            if (startTime == null || endTime == null) {
                return jsonReturn.returnError("开始时间和结束时间不能为空");
            }

            StatsDTO statsDTO = ordersService.getSalesStatsByDateRange(startTime, endTime);
            return jsonReturn.returnSuccess(statsDTO);
        } catch (Exception e) {
            e.printStackTrace();
            return jsonReturn.returnError("获取销售统计数据失败：" + e.getMessage());
        }
    }

}
